import { getAllContentWindow } from '../dom';
import { PlayerWin } from './type';
import { getCurrent, getDomById, playNext } from '../list';

export const getPlayerWin = (): PlayerWin | undefined => {
  return getAllContentWindow().find((win) => (win as any).rePlay) as any;
};

export const getPlayer = () => {
  const win = getPlayerWin();
  const player =  win?.jwplayer('container');
  if(!player) {
    console.error('jwplayer is not found');
  }
  return player;
};

export const play = () => {
  const player = getPlayer();
  player.play();
  return player;
};

export const checkPlay = (onNext?: () => void) => {
  const player = getPlayer();
  const current = getCurrent();

  if (current?.done) {
    playNext();
    onNext?.();
    return;
  }

  if (current.type === 'doc' || current.type === 'text') {
    getDomById(getCurrent().id).trigger('click');
  }

  if (player?.getState()?.toUpperCase() !== 'PLAYING') {
    player?.play();
  }
};

export const getPlayStatus = () => {
  const player = getPlayerWin();
  return {
    basePath: player.basePath,
    userLoginType: player.userLoginType,
    courseId: player.courseId,
    itemId: player.itemId,
    videoResource: player.videoResource,
    videoDefinition: player.videoDefinition,
    videoTime: player.videoTime,
    videoJpg: player.videoJpg,
    videoOrigin: player.videoOrigin,
    captionUrl: player.captionUrl,
    video_bullet_config: player.video_bullet_config,
    videoSpeed: player.videoSpeed,
    videoSpeedRates: player.videoSpeedRates,
    video_trajectory_config: player.video_trajectory_config,
    jwplaySeekTimer: player.jwplaySeekTimer,
    transcodeType: player.transcodeType,
    language: player.language,
    maxSeekPosition: player.maxSeekPosition,
    maxStudyPosition: player.maxStudyPosition,
    autoPlayConfig: player.autoPlayConfig,
    challengeConfig: player.challengeConfig,
    trialDuration: player.trialDuration,
    isTrialTotal: player.isTrialTotal,
  };
};
